
package com.wutianyi.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.ByteChannel;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class Client {

	public static void main(String[] args) {

		try {
			SocketChannel client = SocketChannel.open();
			Selector selector = Selector.open();
			client.configureBlocking(false);
			boolean result = client.connect(new InetSocketAddress("127.0.0.1", 8888));
			// client.finishConnect();
			if(result) {
				System.out.println("yes");
			}else {
				System.out.println("no");
			}
//			client.close();
			SelectionKey key = client.register(selector, SelectionKey.OP_CONNECT);

			for(;;) {
				selector.select();
				Iterator<SelectionKey> keys = selector.selectedKeys().iterator();
				System.out.println(1);
				while(keys.hasNext()) {
					SelectionKey k = keys.next();
					if(k.isConnectable()) {
						SocketChannel socketChannel = (SocketChannel)k.channel();
						if(socketChannel.isConnectionPending()) {
							socketChannel.finishConnect();
						}
						System.out.println("connection");
						socketChannel.write(ByteBuffer.wrap("hello world".getBytes()));
						socketChannel.register(selector, SelectionKey.OP_READ);
					}
					if(k.isReadable()) {
						System.out.println("read");
					}
					keys.remove();
//					if(k.isWritable()) {
//						SocketChannel socketChannel = (SocketChannel)k.channel();
//						System.out.println("writer Data!");
//						ByteBuffer buffer = ByteBuffer.wrap("hello world".getBytes());
//						buffer.flip();
//						socketChannel.write(buffer);
//						k.cancel();
//					}
				}
				selector.selectedKeys().clear();
			}
		}catch(IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
